package com.gitlab.lucky.weixin.web.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.gitlab.lucky.common.dao.model.*;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.result.R;
import com.gitlab.lucky.common.service.ConfigDataService;
import com.gitlab.lucky.common.service.PlatformDataService;
import com.gitlab.lucky.common.utils.CookieUtil;
import com.gitlab.lucky.common.utils.PhoneUtil;
import com.gitlab.lucky.common.utils.TemplateMessageUtil;
import com.gitlab.lucky.eleme.model.ImageResult;
import com.gitlab.lucky.eleme.model.SendCodeResult;
import com.gitlab.lucky.eleme.service.ActivityService;
import com.gitlab.lucky.eleme.service.LuckyRecordService;
import com.gitlab.lucky.eleme.service.WeixinGzhUserCookieService;
import com.gitlab.lucky.weixin.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2019-03-21 15:03
 **/
@Controller
//@CrossOrigin
public class UserInfoController {
    public static final Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);
    //auth url
    private final static String AUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    //get openid
    private final static String OPENID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    private final static String URL = "http://wm.cgygeo.com";
    @Autowired
    private WeixinGzhUserService weixinGzhUserService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private ConfigDataService configDataService;
    @Autowired
    private LuckyRecordService luckyRecordService;
    @Autowired
    private PlatformDataService platformDataService;
    @Autowired
    private WeixinGzhIntegrationRecordService weixinGzhIntegrationRecordService;
    @Autowired
    private WeixinGzhUserCookieService weixinGzhUserCookieService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private WeixinGzhRechargeService weixinGzhRechargeService;
    @Autowired
    private WeixinGzhMsgService weixinGzhMsgService;
    @GetMapping("elem")
    public String elem(){
        return "test";
    }
    //获取code
    @GetMapping("code")
    public String code(Integer platform, String redirectUrl) {
        PlatformData platformData = platformDataService.getPlatform(platform);
        String auth = URLEncoder.encode(URL + "/auth?platform=" + platform + "&redirectUrl=" + redirectUrl);
        //获取code
        String url = String.format(AUTH_URL, platformData.getAppId(), auth);
        //跳转到auth并且获取code
        return "redirect:" + url;
    }
    @GetMapping("testView")
    public String view(){
        return "test";
    }
    //重定向过来,拿到code
    @GetMapping("auth")
    public String auth(String code, Integer platform, HttpServletResponse response, String redirectUrl) {
        PlatformData platformData = platformDataService.getPlatform(platform);
        String url = String.format(OPENID_URL, platformData.getAppId(), platformData.getAppSceart(), code);
        String json = HttpUtil.get(url);
        String openId = JSONObject.parseObject(json).getString("openid");
        Cookie cookie = new Cookie(Constant.OPENID+platform, openId);
        cookie.setMaxAge(60 * 60 * 24 * 30);
        response.addCookie(cookie);
        if(redirectUrl.contains("!")){
            redirectUrl = redirectUrl.replaceAll("!", "&");
            LOGGER.info(redirectUrl);
        }
        return "redirect:" + redirectUrl;
    }

    /**
     * 个人中心
     *
     * @param request
     * @param platform
     * @return
     * @throws IOException
     */
    @GetMapping("infoView")
    public ModelAndView infoView(HttpServletResponse response,HttpServletRequest request, Integer platform) throws IOException {
        if(platform==null){
            return null;
        }
        String openId = CookieUtil.getCookie(request, Constant.OPENID + platform);
        JSONObject json = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            weixinGzhUserService.insertUserInfo(openId, platform, json);
        }
        if (StringUtils.isNotBlank(openId)) {
            ModelAndView mv = new ModelAndView();
            //用户信息
            WeixinGzhUser wx = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
            //公告
            List<Notice> noticeList = noticeService.selectNoticeList(platform);
            //配置
            JSONObject config = configDataService.getConfig(platform);
            //累计优惠金额
            Double totalMoney = luckyRecordService.selectLuckyRecordMoneyByOpenId(openId, platform);
            //佣金
            HashMap<Integer, Double> commission = weixinGzhRechargeService.selectCommission(openId, platform,Constant.WITHDRAWAL_FAIL);
            //共邀请人数
            int inviteCount = 0;
            if (wx != null && StringUtils.isNotBlank(wx.getOpenid())) {
                inviteCount = weixinGzhUserService.selectInviteCount(wx.getOpenid(), platform);
            }
            //是否是管理员
            int isLeader = 0;
            //由3平台管理
            if(platform == 3){
                String leader = config.getString(Constant.LEADER);
                String[] openids = leader.split(",");
                for (int i=0;i<openids.length;i++){
                    if(openId.equals(openids[i])){
                        isLeader = 1;
                    }
                }
            }

            //cps
            int isCps = 0;
            if(platform == 2){
                String leader = config.getString(Constant.IS_CPS);
                String[] openids = leader.split(",");
                for (int i=0;i<openids.length;i++){
                    if(openId.equals(openids[i])){
                        isCps = 1;
                    }
                }
            }
            mv.setViewName("info");
            mv.addObject("nickname", wx.getNickname());
            mv.addObject("headImageUrl", wx.getHeadimgurl());
            mv.addObject("recharge", config.getString(Constant.RECHARGE_URL));
            mv.addObject("notice", noticeList);
            mv.addObject("integration", wx.getIntegration());
            mv.addObject("phone", wx.getPhone());
            mv.addObject("inviteCount", inviteCount);
            mv.addObject("platform", platform);
            mv.addObject("openId", openId);
            mv.addObject("totalMoney",totalMoney);
            mv.addObject("isLeader",isLeader);
            mv.addObject("isCps",isCps);
            mv.addObject("wChatUrl",config.getString(Constant.WECHAT_URL));
            //未提现
            mv.addObject("noWithdrawal",commission.get(Constant.NO_WITHDRAWAL)*json.getDouble(Constant.COMMISSION));
            //已提现
            mv.addObject("withdrawalSuccess",commission.get(Constant.WITHDRAWAL_SUCCESS)*json.getDouble(Constant.COMMISSION));
            //审核中
            mv.addObject("withdrawal",commission.get(Constant.WITHDRAWAL)*json.getDouble(Constant.COMMISSION));
            return mv;
        }
        response.sendRedirect("/code?platform=" + platform + "&redirectUrl=/infoView?platform="+platform);
        return null;
    }
    /**
     * 查询我的邀请记录
     */
    @GetMapping("inviteList")
    @ResponseBody
    public R inviteList(Integer pageNum,Integer pageSize,String openId, Integer platform) {
        PageInfo<WeixinGzhUser> weixinGzhUserList = weixinGzhUserService.selectInviteList(pageNum, pageSize,openId, platform);
        return R.ok().data(weixinGzhUserList);
    }
    /**
     * 我的佣金
     */
    @GetMapping("commission")
    @ResponseBody
    public R commission(Integer pageNum,Integer pageSize,String openId, Integer platform) {
        PageInfo<WeixinGzhRecharge> weixinGzhUserList = weixinGzhRechargeService.selectCommissionInfo(pageNum,pageSize,openId,platform);
        return R.ok().data(weixinGzhUserList);
    }
    /**
     * 邀请每日排行
     */
    @GetMapping("rankingList")
    @ResponseBody
    public R rankingList(Integer platform) {
        List<WeixinGzhUser> weixinGzhUserList = weixinGzhUserService.selectInviteRankingList(platform);
        return R.ok().data(weixinGzhUserList);
    }

    /**
     * 查询我的流水
     */
    @GetMapping("integrationRecord")
    @ResponseBody
    public R integrationRecord(Integer pageNum,Integer pageSize,String openId,Integer platform){
        PageInfo<WeixinGzhIntegrationRecord> weixinGzhIntegrationRecordPageInfo = weixinGzhIntegrationRecordService.selectRecordByOpenId(pageNum, pageSize, openId, platform);
        return R.ok().data(weixinGzhIntegrationRecordPageInfo);
    }
    /**
     * 查询我的领取记录
     *
     * @param openId
     * @param platform
     * @return
     */
    @GetMapping("luckyRecord")
    @ResponseBody
    public R luckyRecord(Integer pageNum,Integer pageSize,String openId, Integer platform) {
        PageInfo<LuckyRecord> luckyRecords = luckyRecordService.selectLuckyRecordByOpenId(pageNum, pageSize,openId, platform);
        return R.ok().data(luckyRecords);
    }
    /**
     * 活动页面
     * @param request
     * @param response
     * @param platform
     * @return
     * @throws IOException
     */
    @GetMapping("activity")
    public ModelAndView activity(HttpServletRequest request, HttpServletResponse response, Integer platform) throws IOException {
        if(platform==null){
            return null;
        }
        String openId = CookieUtil.getCookie(request, Constant.OPENID + platform);
        if (StringUtils.isBlank(openId)) {
            response.sendRedirect("/code?platform=" + platform + "&redirectUrl=/activity");
            return null;
        }
        JSONObject json = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, json);
        }
        ModelAndView mv = new ModelAndView();
        //用户信息
        mv.setViewName("activity");
        mv.addObject("recha", String.format(json.getString(Constant.ACTIVITY_DESCRIPTION),json.getString(Constant.ACTIVITY_INTEGRAL)));
        mv.addObject("nickname", wxUserInfo.getNickname());
        mv.addObject("integration", wxUserInfo.getIntegration());
        mv.addObject("phone", wxUserInfo.getPhone());
        mv.addObject("platform", wxUserInfo.getPlatform());
        mv.addObject("openId", wxUserInfo.getOpenid());
        mv.addObject("title", json.getString(Constant.ACTIVITY_TITLE));
        return mv;
    }

    /**
     * 发送短信，返回图片验证码
     * @param phone
     * @param platform
     * @param openId
     * @return
     */
    @RequestMapping("sendSMS")
    @ResponseBody
    public R sendSMS(String phone, Integer platform, String openId) {
        if(!PhoneUtil.isNum(phone)){
            return R.error("您输入的手机号码有误");
        }
        JSONObject json = configDataService.getConfig(platform);
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (weixinGzhUser.getIntegration() < json.getInteger(Constant.ACTIVITY_INTEGRAL)) {
            return R.error(300, json.getString(Constant.RECHARGE_URL));
        }
        //图片验证码
        ImageResult imageResult = ActivityService.sendMsg(phone);
        return R.ok().data(imageResult);
    }

    /**
     * 验证图片验证码和手机验证码
     * @param captcha
     * @param hash
     * @param phone
     * @return
     */
    @RequestMapping("captcha")
    @ResponseBody
    public R captcha(String captcha, String hash, String phone) {
        if (captcha.length() == Constant.IMAGE_CODE_LENGTH) {
            SendCodeResult sendCodeResult = ActivityService.sendSMS(phone, captcha, hash);
            if (sendCodeResult != null && StringUtils.isNotBlank(sendCodeResult.getValidate_token())) {
                return R.ok().data(sendCodeResult.getValidate_token());
            } else {
                return R.error(sendCodeResult.getMessage());
            }
        }
        return R.error("请输入正确的验证码");
    }

    /**
     * 开通超级会员
     * @param smsCode
     * @param token
     * @param phone
     * @param platform
     * @param openId
     * @return
     */
    @RequestMapping("checkPhoneCode")
    @ResponseBody
    public R checkPhoneCode(String smsCode, String token, String phone, Integer platform, String openId) {
        JSONObject configJSON = configDataService.getConfig(platform);
        if (PhoneUtil.isCode(smsCode)) {
            WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
            String cookie = ActivityService.login(phone, smsCode, token);
            LOGGER.info("登陆完成,cookie={}",cookie);
            if (!cookie.contains("USERID=")) {
                return R.error("验证码输入错误");
            } else {
                //JSONObject json = activityService.lucky(cookie);
                JSONObject json = activityService.superMember(cookie);
                LOGGER.info(json.toJSONString());
                String data = json.getString("code");
                WeixinGzhUserCookie weixinGzhUserCookie = new WeixinGzhUserCookie();
                weixinGzhUserCookie.setCookie(cookie);
                weixinGzhUserCookie.setOpenId(weixinGzhUser.getOpenid());
                weixinGzhUserCookieService.insertSelective(weixinGzhUserCookie);
                if (data.equals("200")) {
                    LOGGER.info("领取超级会员,状态,({}),平台:({}),用户:({})", Constant.SUCCESS, platform, phone);
                    Integer count = weixinGzhUser.getIntegration() - configJSON.getInteger(Constant.ACTIVITY_INTEGRAL);
                    weixinGzhUser.setIntegration(count);
                    weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);

                    WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
                    weixinGzhIntegrationRecord.setCreateTime(new Date());
                    weixinGzhIntegrationRecord.setPlatform(platform);
                    weixinGzhIntegrationRecord.setType(CodeEnum.SUPER_MEMBER.getCode());
                    weixinGzhIntegrationRecord.setOpenId(weixinGzhUser.getOpenid());
                    weixinGzhIntegrationRecord.setIntegration("-"+configJSON.getInteger(Constant.ACTIVITY_INTEGRAL));
                    weixinGzhIntegrationRecord.setIntegrationBalance(count);
                    weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);
                    return R.ok().data(configJSON.getString(Constant.ACTIVITY_SUCCESS));
                }
                //未配置红包
                if (data.equals("1103")) {
                    LOGGER.info("领取超级会员,状态,({}),平台:({}),用户:({})", 1003, platform, phone);
                    return R.error(configJSON.getString(Constant.ACTIVITY_FAIL));
                }
                LOGGER.info("领取超级会员,状态,({}),平台:({}),用户:({}),饿了么返回:({})", Constant.FAIL, platform, phone, json.toJSONString());
                return R.error(json.getString("message"));
            }
        }
        return R.error();
    }

    /**
     * 流水页面
     * @return
     */
    @GetMapping("integrationRecordView")
    public ModelAndView integrationRecordView(String openId,Integer platform){
        ModelAndView mv = new ModelAndView();
        mv.addObject("openId",openId);
        mv.addObject("platform",platform);
        mv.setViewName("integrationRecord");
        return mv;
    }
    /**
     * 查询我的邀请记录
     */
    @GetMapping("inviteListView")
    public ModelAndView inviteListView(String openId, Integer platform) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("openId",openId);
        mv.addObject("platform",platform);
        mv.setViewName("inviteRecord");
        return mv;
    }
    /**
     * 查询邀请排行榜
     */
    @GetMapping("rankingListView")
    public ModelAndView rankingListView(Integer platform) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("platform",platform);
        mv.setViewName("rankingList");
        return mv;
    }
    /**
     * 我的佣金
     */
    @GetMapping("commissionView")
    @ResponseBody
    public ModelAndView commissionView(String openId, Integer platform) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("openId",openId);
        mv.addObject("platform",platform);
        mv.setViewName("commission");
        return mv;
    }
    /**
     * 查询我的领取记录
     *
     * @return
     */
    @GetMapping("luckyRecordView")
    public ModelAndView luckyRecordView(String openId, Integer platform) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("openId",openId);
        mv.addObject("platform",platform);
        mv.setViewName("luckyRecord");
        return mv;
    }

    /**
     * 平台红包统计
     * @param openId
     * @return
     */
    @GetMapping("remainingMoneyView")
    public ModelAndView remainingMoneyView(String openId){
        ModelAndView mv = new ModelAndView();
        //取平台信息
        PlatformData platformData = platformDataService.getPlatformDataByOpenId(openId);
        //该平台已用红包数量
        Integer luckyCount = luckyRecordService.selectLuckyRecordCountByPlaform(platformData.getPlatform());
        //平台名称
        mv.addObject("nickName",platformData.getNickname());
        //已用红包数量
        mv.addObject("luckyCount",luckyCount);
        //剩余红包数量
        mv.addObject("remainingNumber",platformData.getPlaceNumber()-luckyCount);
        mv.setViewName("remainingMoney");
        return mv;
    }

    /**
     * CPS
     * @param platform
     * @return
     */
    @GetMapping("cpsMoneyView")
    public ModelAndView cpsMoneyView(Integer platform){
        ModelAndView mv = new ModelAndView();
        JSONObject json = configDataService.getConfig(platform);
        mv.addObject("orderNum",json.getString(Constant.ORDER_NUM));
        mv.addObject("money",json.getString(Constant.MONEY_CPS));
        mv.setViewName("cpsMoney");
        return mv;
    }


    /**
     * 饿了么礼包  "obXBS5tGFgq1jDOJ_VwdIgEzt0ro";//
     * @param request
     * @param response
     * @param platform
     * @return
     * @throws IOException
     */
    @GetMapping("elmlbView")
    public ModelAndView elmlbView(HttpServletRequest request, HttpServletResponse response, Integer platform) throws IOException {
        if(platform==null){
            return null;
        }
        String openId =  CookieUtil.getCookie(request, Constant.OPENID + platform);
        if (StringUtils.isBlank(openId)) {
            response.sendRedirect("/code?platform=" + platform + "&redirectUrl=/elmlbView");
            return null;
        }
        JSONObject json = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, json);
        }
        ModelAndView mv = new ModelAndView();
        //用户信息
        mv.setViewName("elmlb");
        mv.addObject("recharge_url", json.getString(Constant.RECHARGE_URL));
        mv.addObject("nickname", wxUserInfo.getNickname());
        mv.addObject("integration", wxUserInfo.getIntegration());
        mv.addObject("phone", wxUserInfo.getPhone());
        mv.addObject("platform", wxUserInfo.getPlatform());
        mv.addObject("openId", wxUserInfo.getOpenid());
        mv.addObject("integral",json.getInteger(Constant.MIN_COUNT));
        mv.addObject("wechat_url",json.getString(Constant.WECHAT_URL));
        return mv;
    }

    /**
     * 饿了么批量
     * @param request
     * @param response
     * @param platform
     * @return
     * @throws IOException
     */
    @GetMapping("elmplView")
    public ModelAndView elmplView(HttpServletRequest request, HttpServletResponse response, Integer platform) throws IOException {
        if(platform==null){
            return null;
        }
        String openId = CookieUtil.getCookie(request, Constant.OPENID + platform);
        if (StringUtils.isBlank(openId)) {
            response.sendRedirect("/code?platform=" + platform + "&redirectUrl=/elmplView");
            return null;
        }
        JSONObject json = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, json);
        }
        ModelAndView mv = new ModelAndView();
        //用户信息
        mv.setViewName("elmpl");
        mv.addObject("recharge_url", json.getString(Constant.RECHARGE_URL));
        mv.addObject("nickname", wxUserInfo.getNickname());
        mv.addObject("integration", wxUserInfo.getIntegration());
        mv.addObject("phone", wxUserInfo.getPhone());
        mv.addObject("platform", wxUserInfo.getPlatform());
        mv.addObject("openId", wxUserInfo.getOpenid());
        mv.addObject("integral",json.getInteger(Constant.MIN_COUNT));
        mv.addObject("wechat_url",json.getString(Constant.WECHAT_URL));
        return mv;
    }



    /**
     * 2平台暂用
     * @param request
     * @param response
     * @param platform
     * @return
     * @throws IOException
     */
    @GetMapping("giftBagView")
    public ModelAndView giftBagView(HttpServletRequest request, HttpServletResponse response, Integer platform) throws IOException {
        if(platform==null){
            return null;
        }
        String openId = CookieUtil.getCookie(request, Constant.OPENID + platform);
        if (StringUtils.isBlank(openId)) {
            response.sendRedirect("/code?platform=" + platform + "&redirectUrl=/giftBagView");
            return null;
        }
        JSONObject json = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, json);
        }
        ModelAndView mv = new ModelAndView();
        //用户信息
        mv.setViewName("giftbag");
        mv.addObject("recharge_url", json.getString(Constant.RECHARGE_URL));
        mv.addObject("openId", openId);
        mv.addObject("nickname", wxUserInfo.getNickname());
        mv.addObject("integration", wxUserInfo.getIntegration());
        mv.addObject("phone", wxUserInfo.getPhone());
        mv.addObject("platform", wxUserInfo.getPlatform());
        mv.addObject("openId", wxUserInfo.getOpenid());
        mv.addObject("integral",json.getInteger(Constant.MIN_COUNT));
        return mv;
    }

    /**
     * 测试应用到数据库是否连通
     * @return
     */
    @GetMapping("/getProbe")
    @ResponseBody
    public String getProbe(){
        try {
            weixinGzhUserService.getWxUserInfoByOpenId("o8zUP1IWzQHanjNPHKeh8o5Ds48M", 1);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString("error."+e.getMessage());
        }
        return JSON.toJSONString("success");
    }

    @GetMapping("/checkServer")
    private static String checkServer(){
        StringBuffer buffer = new StringBuffer();
        List<String> urls = Arrays.asList("http://127.0.0.1:8001","http://127.0.0.1:8002");
        urls.forEach(v->{
            buffer.append("请求域名：");
            buffer.append(v);
            HttpGet httpget = new HttpGet(v);
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                int responseCode = httpclient.execute(httpget).getStatusLine().getStatusCode();
                buffer.append("  状态："+responseCode);
            } catch (IOException e) {
                buffer.append("  状态："+500);
            }
            buffer.append(" 《===》  ");
        });
        return buffer.toString();
    }

    /**
     * 记录积分流水 发送消费通知
     * @param openId
     * @param platform
     * @param wxUserInfo
     * @param type
     * @param money
     * @param json
     */
    public void weixinGzhIntegrationRecord(String openId,Integer platform,WeixinGzhUser wxUserInfo,Integer type,String money,JSONObject json){
        //积分流水
        WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
        weixinGzhIntegrationRecord.setCreateTime(new Date());
        weixinGzhIntegrationRecord.setPlatform(platform);
        Integer integral = json.getInteger(Constant.MIN_COUNT);
        if(type == 1 || type == 2){
            weixinGzhIntegrationRecord.setType(CodeEnum.LUCKY_API.getCode());
            //类型1、2的小于4扣积分
            if(Double.parseDouble(money)>=4){
                money = String.valueOf(5);
            }
        }else{
            weixinGzhIntegrationRecord.setType(CodeEnum.GIFTBAG_API.getCode());
        }
        weixinGzhIntegrationRecord.setOpenId(wxUserInfo.getOpenid());
        if(Double.parseDouble(money)>=5){
            weixinGzhIntegrationRecord.setIntegration("-"+integral);
            weixinGzhIntegrationRecord.setIntegrationBalance(wxUserInfo.getIntegration()-integral);

            //积分消耗
            wxUserInfo.setIntegration(wxUserInfo.getIntegration()-integral);
            weixinGzhUserService.updateByPrimaryKeySelective(wxUserInfo);

            //发送通知
            if(json.getInteger(Constant.IS_TEMPLATE) == 1) {
                PlatformData platformData = platformDataService.getPlatform(platform);
                List<TemplateMessageUtil> templateParams = new ArrayList<>();
                TemplateMessageUtil first = new TemplateMessageUtil("first", "", "");
                TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", platformData.getRemark(), "");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");
                TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", sdf.format(new Date()),"");
                TemplateMessageUtil keyword3 = new TemplateMessageUtil("keyword3", integral+"积分","");
                TemplateMessageUtil keyword4 = new TemplateMessageUtil("keyword4", df.format(new Date()),"");
                TemplateMessageUtil remark = new TemplateMessageUtil("remark", "感谢您的使用。", "");
                templateParams.add(first);
                templateParams.add(keyword1);
                templateParams.add(keyword2);
                templateParams.add(keyword3);
                templateParams.add(keyword4);
                templateParams.add(remark);
                String url = Constant.DOMAIN_URL+"/integrationRecordView?openId="+openId+"&platform="+platform;
                weixinGzhMsgService.sendWarningByWechat(openId, platform,json.getString(Constant.CONSUMPTION_TEMPLATE_ID), templateParams,url);
            }
        }else{
            weixinGzhIntegrationRecord.setIntegration("-0");
            weixinGzhIntegrationRecord.setIntegrationBalance(wxUserInfo.getIntegration()-0);
        }

        weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);
    }

    /**
     * 每日礼包一领取
     * @param openId
     * @param phone
     * @param type 5每日礼包
     * @param validateToken
     * @param validateCode
     * @param platform
     * @param receiveType 手机号请求1，验证码请求2
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @PostMapping("dayPacket")
    public R dayPacket(String openId,String phone,Integer type,String validateToken,String validateCode, Integer platform,Integer receiveType) throws InterruptedException {
        if (platform == null) {
            return null;
        }
        PlatformData platformData = platformDataService.getPlatform(platform);
        LOGGER.info("\n每日礼包一领取基本信息" + openId + "," + phone + "," + type + "," + validateToken + "," + validateCode + "," + platform);
        JSONObject configJson = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, configJson);
        }
        if(wxUserInfo.getPhone() == null || "".equals(wxUserInfo.getPhone())){
            weixinGzhUserService.updateUserInfo(openId, phone, platform);
        }
        Integer integral = configJson.getInteger(Constant.MIN_COUNT);
        if (wxUserInfo.getIntegration() < integral) {
            return R.error("积分不足,请及时充值");
        }
        JSONObject requestJson = new JSONObject();
        requestJson.put("phone",phone);
        requestJson.put("receiveType",receiveType);
        requestJson.put("packType",3);
        if (StringUtils.isNotBlank(validateCode) && StringUtils.isNotBlank(validateToken)) {
            requestJson.put("validateToken", validateToken);
            requestJson.put("validateCode", validateCode);
        }
        String url = "https://xjj.open.xjj186.cn/elm/place/order";
        HttpRequest request = HttpUtil.createPost(url)
                .header("Content-type", "application/json;charset=utf-8")
                .header("Token", platformData.getToken())
                .body(requestJson.toJSONString()).timeout(25000);
        String body = "";
        try {
            body = request.execute().body();
        }catch (Exception e){
            LOGGER.info("\n|*****************");
            LOGGER.info(String.valueOf(request.execute()));
            LOGGER.info("\n|每日礼包一body解析异常，用户信息"+ openId + "," + phone + "，" + platform);
            LOGGER.info("\n|*****************");
            return R.ok(CodeEnum.DEFEATED);
        }
        cn.hutool.json.JSONObject bodyJson = XML.toJSONObject(body);
        LOGGER.info("\n************每日礼包一返回参数：\n"+bodyJson.toString() + openId + "," + phone + "," + platform);
        JSONObject responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());
        //SID失效 重新调用
        if(responseWrapper.getString("data").contains("失效") || "0007".equals(responseWrapper.getString("code"))){
            LOGGER.info("\n###########返回0007 拆包未满10次\n");
            request = HttpUtil.createPost(url)
                    .header("Content-type", "application/json;charset=utf-8")
                    .header("Token", platformData.getToken())
                    .body(requestJson.toJSONString()).timeout(25000);
            body = "";
            try {
                body = request.execute().body();
            }catch (Exception e){
                LOGGER.info("\n|*****************");
                LOGGER.info("\n|每日礼包一body解析异常，用户信息"+ openId + "," + phone + "，" + platform);
                LOGGER.info("\n|*****************");
                return R.ok(CodeEnum.DEFEATED);
            }
            bodyJson = XML.toJSONObject(body);
            responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());
        }
        if(responseWrapper.getString("data").contains("失效") || "0007".equals(responseWrapper.getString("code"))){
            return R.ok(CodeEnum.CUSTOM);
        }
        String code = responseWrapper.getString("code");
        switch (code){
            case "401":
                //返回validateToken给前台
                return R.ok(CodeEnum.VALIDATE).data(responseWrapper.getString("data"));
            case "0001":
                return R.ok(CodeEnum.RECEIVE);
            case "0002":
                CodeEnum.CUSTOM.setCode(2000);
                if(responseWrapper.getString("msg").contains("饿了么APP")){
                    //接口sid失效 提示重领
                    CodeEnum.CUSTOM.setMsg("请重新领取一下哦！");
                }else{
                    CodeEnum.CUSTOM.setMsg(responseWrapper.getString("msg"));
                }
                return R.ok(CodeEnum.CUSTOM);
            case "0005":
                return R.ok(CodeEnum.SMALL);
            case "0007":
                return R.ok(CodeEnum.CUSTOM);
            case "10016":
                return R.ok(CodeEnum.INVENTORY);
            case "1002":
                return R.ok(CodeEnum.INVENTORY);
            case "0000":
                JSONArray data = (JSONArray) JSONArray.parse(responseWrapper.getString("data"));
                String result = "";
                for (int i = 0; i < data.size(); i++) {
                    JSONObject resultData = JSONObject.parseObject(data.get(i).toString());
                    String description = resultData.getString("description");
                    String amount = resultData.getString("amount");
                    String title = resultData.getString("title");
                    result += "满" + description.substring(1, description.length() - 3) + "减" + amount + " "+ title + ",";

                    //领取记录
                    LuckyRecord luckyRecord = new LuckyRecord();
                    luckyRecord.setOpenid(openId);
                    luckyRecord.setIsSuccess(Constant.TRUE);
                    luckyRecord.setCreateTime(new Date());
                    luckyRecord.setPlatform(platform);
                    luckyRecord.setLuckyMoney(Double.parseDouble(amount));
                    luckyRecordService.insert(luckyRecord);
                }

                weixinGzhIntegrationRecord(openId,platform, wxUserInfo,type,"5",configJson);
                LOGGER.info("\n************每日礼包一领取成功\n" + result + openId + "," + phone + "," + platform);
                return R.ok().data(result.substring(0,result.length()-1));
        }

        return R.error().data(responseWrapper);
    }

    /**
     * 饿了么大红包(免码)  暂停
     * @param openId
     * @param phone
     * @param type 1=品质联盟，2=拼手气
     * @param validateToken
     * @param validateCode
     * @param platform
     * @param receiveType 1=手机号领取，2=验证码领取
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @PostMapping("spellLuck")
    public R spellLuck(String openId,String phone,Integer type,String validateToken,String validateCode, Integer platform,Integer receiveType) throws InterruptedException {
        if (platform == null) {
            return null;
        }
        PlatformData platformData = platformDataService.getPlatform(platform);
        LOGGER.info("\n饿了么大红包领取基本信息" + openId + "," + phone + "," + type + "," + validateToken + "," + validateCode + "," + platform);
        JSONObject configJson = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, configJson);
        }
        if(wxUserInfo.getPhone() == null || "".equals(wxUserInfo.getPhone())){
            weixinGzhUserService.updateUserInfo(openId, phone, platform);
        }
        Integer integral = configJson.getInteger(Constant.MIN_COUNT);
        if (wxUserInfo.getIntegration() < integral) {
            return R.error("积分不足,请及时充值");
        }
        JSONObject requestJson = new JSONObject();
        requestJson.put("phone",phone);
        requestJson.put("receiveType",receiveType);
        requestJson.put("packType",type);
        if (StringUtils.isNotBlank(validateCode) && StringUtils.isNotBlank(validateToken)) {
            requestJson.put("validateToken", validateToken);
            requestJson.put("validateCode", validateCode);
        }
        String url = "https://xjj.open.xjj186.cn/elm/easy/luck";
        HttpRequest request = HttpUtil.createPost(url)
                .header("Content-type", "application/json;charset=utf-8")
                .header("Token", platformData.getToken())
                .body(requestJson.toJSONString()).timeout(25000);
        String body = request.execute().body();
        cn.hutool.json.JSONObject bodyJson = XML.toJSONObject(body);
        LOGGER.info("\n*************饿了么大红包返回参数一："+bodyJson.toString() + openId + "," + phone + "," + platform);
        JSONObject responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());
        String code = responseWrapper.getString("code");
        switch (code){
            case "401":
                //返回validateToken给前台
                return R.ok(CodeEnum.VALIDATE).data(responseWrapper.getString("data"));
            case "2001":
                return R.ok(CodeEnum.FREEZE);
            case "10015":
            case "10016":
                return R.ok(CodeEnum.INVENTORY);
            case "0002" :
            case "20002":
                return R.ok(CodeEnum.FAILURE);
            case "0000":
                String data = responseWrapper.getString("data");
                Thread.sleep(2500);
                HttpRequest get = HttpUtil.createGet("https://xjj.open.xjj186.cn/elm/easy/luck/" + data)
                        .header("Content-type", "application/json;charset=utf-8")
                        .header("Token", platformData.getToken())
                        .timeout(25000);
                cn.hutool.json.JSONObject jsonObjects = XML.toJSONObject(get.execute().body());
                JSONObject responseWrappers = JSON.parseObject(jsonObjects.get("ResponseWrapper").toString());
                String codes = responseWrappers.getString("code");
                LOGGER.info("\n***********饿了么大红包返回参数二"+responseWrappers.toString() + openId + "," + phone + "," + platform);
                if (codes.equals("0000")) {
                    //取接口返回值
                    JSONObject dataJson = JSONObject.parseObject(responseWrappers.getString("data"));
                    String result = "";
                    switch (dataJson.getString("status")){
                        case "1":
                        case "0":
                        case "4":
                            return R.ok(CodeEnum.FAILURE);
                        case "3":
                            return R.ok(CodeEnum.INVENTORY);
                        case "5":
                            return R.ok(CodeEnum.LIMIT);
                        case "2":
                            String sumCondition = dataJson.getString("sumCondition");
                            String money = dataJson.getString("money");
                            String packName = dataJson.getString("packName");
                            if(Double.parseDouble(money)<4){
                                result = "1.您领取到"+money+"元红包,2.本次不消耗积分,3.请间隔5分钟再领取此类型红包,4.建议您先去领取每日礼包";
                            }else{
                                result = "满"+sumCondition + "减" + money + " " + packName;
                            }
                            //领取记录
                            LuckyRecord luckyRecord = new LuckyRecord();
                            luckyRecord.setOpenid(openId);
                            luckyRecord.setIsSuccess(Constant.TRUE);
                            luckyRecord.setCreateTime(new Date());
                            luckyRecord.setPlatform(platform);
                            luckyRecord.setLuckyMoney(Double.parseDouble(money));
                            luckyRecordService.insert(luckyRecord);
                            weixinGzhIntegrationRecord(openId,platform, wxUserInfo,type,money,configJson);
                            LOGGER.info("\n******************饿了么大红包领取成功\n" + result + "\n" + openId + "," + phone + "，" + platform);
                            return R.ok().data(result);
                    }
                }
        }

        return R.error().data(responseWrapper);
    }

    /**
     * 批量礼包
     * @param openId
     * @param phone
     * @param type 4=随机礼包
     * @param validateToken
     * @param validateCode
     * @param platform
     * @param receiveType 1=手机号领取，2=验证码领取
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @PostMapping("activePacket")
    public R activePacket(String openId,String phone,Integer type,String validateToken,String validateCode, Integer platform,Integer receiveType) throws InterruptedException {
        if (platform == null) {
            return null;
        }
        PlatformData platformData = platformDataService.getPlatform(platform);
        LOGGER.info("\n批量礼包领取基本信息" + openId + "," + phone + "," + type + "," + validateToken + "," + validateCode + "," + platform);
        JSONObject configJson = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, configJson);
        }
        if(wxUserInfo.getPhone() == null || "".equals(wxUserInfo.getPhone())){
            weixinGzhUserService.updateUserInfo(openId, phone, platform);
        }
        Integer integral = configJson.getInteger(Constant.MIN_COUNT);
        if (wxUserInfo.getIntegration() < integral) {
            return R.error("积分不足,请及时充值");
        }
        JSONObject requestJson = new JSONObject();
        requestJson.put("phone",phone);
        requestJson.put("receiveType",receiveType);
        if (StringUtils.isNotBlank(validateCode) && StringUtils.isNotBlank(validateToken)) {
            requestJson.put("validateToken", validateToken);
            requestJson.put("validateCode", validateCode);
        }
        String url = "https://xjj.open.xjj186.cn/elm/active/packet";
        HttpRequest request = HttpUtil.createPost(url)
                .header("Content-type", "application/json;charset=utf-8")
                .header("Token", platformData.getToken())
                .body(requestJson.toJSONString()).timeout(25000);
        String body = "";
        try {
            body = request.execute().body();
        }catch (Exception e){
            LOGGER.info("\n|*****************");
            LOGGER.info("\n|批量礼包body解析异常，用户信息"+ openId + "," + phone + "，" + platform);
            LOGGER.info("\n|*****************");
            return R.ok(CodeEnum.DEFEATED);
        }
        cn.hutool.json.JSONObject bodyJson = null;
        try{
            bodyJson = XML.toJSONObject(body);
        }catch (Exception e){
            //接口返回502 mlb
            return R.ok(CodeEnum.SERVER_INTERNAL_ERROR);
        }
        LOGGER.info("\n批量礼包返回参数：\n"+bodyJson.toString() + openId + "," + phone + "," + platform);
        JSONObject responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());
        String code = responseWrapper.getString("code");
        switch (code){
            case "401":
                //返回validateToken给前台
                return R.ok(CodeEnum.VALIDATE).data(responseWrapper.getString("data"));
            case "0001":
                return R.ok(CodeEnum.RECEIVE);
            case "0002":
                CodeEnum.CUSTOM.setCode(2000);
                CodeEnum.CUSTOM.setMsg(responseWrapper.getString("msg"));
                return R.ok(CodeEnum.CUSTOM);
            case "0005":
                return R.ok(CodeEnum.SMALL);
            case "10016":
                return R.ok(CodeEnum.INVENTORY);
            case "0000":
                JSONArray data = null;
                try{
                    //这个b接口有时返回jsonarray 有时返回jsonobject
                    data = (JSONArray) JSONArray.parse(responseWrapper.getString("data"));
                }catch (Exception e){
                    return R.ok(CodeEnum.RECEIVE);
                }
                String result = "";
                String luckyMoney = "5";
                for (int i = 0; i < data.size(); i++) {
                    JSONObject resultData = JSONObject.parseObject(data.get(i).toString());
                    String threshold = resultData.getString("threshold");
                    String amount = resultData.getString("amount");
                    String title = resultData.getString("title");
                    result += "满" + threshold + "减" + amount + " " + title + ",";
                    //小于4不扣积分
                    if( Integer.parseInt(threshold) == 150 || Integer.parseInt(threshold) == 100){
                        luckyMoney = "1";
                    }
                    //领取记录
                    LuckyRecord luckyRecord = new LuckyRecord();
                    luckyRecord.setOpenid(openId);
                    luckyRecord.setIsSuccess(Constant.TRUE);
                    luckyRecord.setCreateTime(new Date());
                    luckyRecord.setPlatform(platform);
                    luckyRecord.setLuckyMoney(Double.parseDouble(amount));
                    luckyRecordService.insert(luckyRecord);
                }

                weixinGzhIntegrationRecord(openId,platform, wxUserInfo,type,luckyMoney,configJson);
                LOGGER.info("\n************批量礼包领取成功\n" + result + openId + "," + phone + "，" + platform);
                if("1".equals(luckyMoney)){
                    return R.ok().data("本次领取不消耗积分," + result.substring(0,result.length()-1));
                }
                return R.ok().data(result.substring(0,result.length()-1));
        }

        return R.error().data(responseWrapper);
    }


    /**
     * 通用组合红包
     * @param openId
     * @param phone
     * @param type
     * @param validateToken
     * @param validateCode
     * @param platform
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @PostMapping("generalLucky")
    public R generalLucky(String openId,String phone,Integer type,String validateToken,String validateCode, Integer platform) throws InterruptedException {
        if (platform == null) {
            return null;
        }
        PlatformData platformData = platformDataService.getPlatform(platform);
        LOGGER.info("\n通用红包领取基本信息" + openId + "," + phone + "," + type + "," + validateToken + "," + validateCode + "," + platform);
        JSONObject configJson = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, configJson);
        }
        if(wxUserInfo.getPhone() == null || "".equals(wxUserInfo.getPhone())){
            weixinGzhUserService.updateUserInfo(openId, phone, platform);
        }
        Integer integral = configJson.getInteger(Constant.MIN_COUNT);
        if (wxUserInfo.getIntegration() < integral) {
            return R.error("积分不足,请及时充值");
        }
        JSONObject requestJson = new JSONObject();
        requestJson.put("phone",phone);
        requestJson.put("packType",4);
        requestJson.put("receiveType",6);
        if (StringUtils.isNotBlank(validateCode) && StringUtils.isNotBlank(validateToken)) {
            requestJson.put("validateToken", validateToken);
            requestJson.put("validateCode", validateCode);
        }
        String url = "https://xjj.open.xjj186.cn/elm/place/order";
        HttpRequest request = HttpUtil.createPost(url)
                .header("Content-type", "application/json;charset=utf-8")
                .header("Token", platformData.getToken())
                .body(requestJson.toJSONString()).timeout(25000);
        String body = "";
        try {
            body = request.execute().body();
        }catch (Exception e){
            LOGGER.info("\n|*****************");
            LOGGER.info("\n|通用礼包body解析异常，用户信息"+ openId + "," + phone + "，" + platform);
            LOGGER.info("\n|*****************");
            return R.ok(CodeEnum.DEFEATED);
        }
        cn.hutool.json.JSONObject bodyJson = null;
        try{
            bodyJson = XML.toJSONObject(body);
        }catch (Exception e){
            //接口返回502 mlb
            return R.ok(CodeEnum.SERVER_INTERNAL_ERROR);
        }
        LOGGER.info("\n通用礼包返回参数：\n"+bodyJson.toString() + openId + "," + phone + "," + platform);
        JSONObject responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());
        String code = responseWrapper.getString("code");
        switch (code){
            case "401":
                //返回validateToken给前台
                return R.ok(CodeEnum.VALIDATE).data(responseWrapper.getString("data"));
            case "0001":
                return R.ok(CodeEnum.DEFEATED);
            case "0002":
                return R.ok(CodeEnum.DEFEATED);
            case "0005":
                return R.ok(CodeEnum.SMALL);
            case "10016":
                return R.ok(CodeEnum.INVENTORY);
            case "0000":
                JSONArray data = null;
                try{
                    //这个b接口有时返回jsonarray 有时返回jsonobject
                    data = (JSONArray) JSONArray.parse(responseWrapper.getString("data"));
                }catch (Exception e){
                    return R.ok(CodeEnum.RECEIVE);
                }
                String result = "";
                String luckyMoney = "1";
                for (int i = 0; i < data.size(); i++) {
                    JSONObject resultData = JSONObject.parseObject(data.get(i).toString());
                    String threshold = resultData.getString("threshold");
                    String amount = resultData.getString("amount");
                    String title = resultData.getString("title");
                    if(!"1".equals(amount)){
                        result += "满" + threshold + "减" + amount + " " + title + ",";
                    }
                    //小于4不扣积分
                    if(Double.parseDouble(amount)>=4 && title.contains("通用红包")){
                        luckyMoney = "5";
                    }
                    //领取记录
                    LuckyRecord luckyRecord = new LuckyRecord();
                    luckyRecord.setOpenid(openId);
                    luckyRecord.setIsSuccess(Constant.TRUE);
                    luckyRecord.setCreateTime(new Date());
                    luckyRecord.setPlatform(platform);
                    luckyRecord.setLuckyMoney(Double.parseDouble(amount));
                    if(!"1".equals(amount)){
                        luckyRecordService.insert(luckyRecord);
                    }
                }

                weixinGzhIntegrationRecord(openId,platform, wxUserInfo,type,luckyMoney,configJson);
                LOGGER.info("\n************通用红包领取成功\n" + result + "\n" + openId + "," + phone + "，" + platform);
                if("1".equals(luckyMoney)){
                    return R.ok().data("因红包金额低于5元,本次不消耗积分,先去领取其他类型红包吧,如有问题请联系客服"/* + result.substring(0,result.length()-1)*/);
                }
                return R.ok().data(result.substring(0,result.length()-1));
        }

        return R.error().data(responseWrapper);
    }


    /**
     * 品质联盟35-5 通用35-5
     * @param openId
     * @param phone
     * @param type
     * @param validateToken
     * @param validateCode
     * @param platform
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @PostMapping("pinzhi")
    public R pinzhi(String openId,String phone,Integer type,String validateToken,String validateCode, Integer platform,Integer receiveType) throws InterruptedException {
        if (platform == null) {
            return null;
        }
        PlatformData platformData = platformDataService.getPlatform(platform);
        LOGGER.info("\n品质35-5领取基本信息" + openId + "," + phone + "," + type + "," + validateToken + "," + validateCode + "," + platform);
        JSONObject configJson = configDataService.getConfig(platform);
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        if (wxUserInfo == null) {
            wxUserInfo = weixinGzhUserService.insertUserInfo(openId, platform, configJson);
        }
        if(wxUserInfo.getPhone() == null || "".equals(wxUserInfo.getPhone())){
            weixinGzhUserService.updateUserInfo(openId, phone, platform);
        }
        Integer integral = configJson.getInteger(Constant.MIN_COUNT);
        if (wxUserInfo.getIntegration() < integral) {
            return R.error("积分不足,请及时充值");
        }
        int packType = 12;
        String flag = "";
        if(type == 8){
            receiveType = 6;
            flag = "品质35-5";
        }
        if(type == 10){
            packType = 13;
            receiveType = receiveType;
            flag = "通用35-5";
        }
        JSONObject requestJson = new JSONObject();
        requestJson.put("phone",phone);
        requestJson.put("packType",packType);
        requestJson.put("receiveType",receiveType);
        if (StringUtils.isNotBlank(validateCode) && StringUtils.isNotBlank(validateToken)) {
            requestJson.put("validateToken", validateToken);
            requestJson.put("validateCode", validateCode);
        }
        String url = "https://xjj.open.xjj186.cn/elm/place/order";
        HttpRequest request = HttpUtil.createPost(url)
                .header("Content-type", "application/json;charset=utf-8")
                .header("Token", platformData.getToken())
                .body(requestJson.toJSONString()).timeout(25000);
        String body = "";
        try {
            body = request.execute().body();
        }catch (Exception e){
            LOGGER.info("\n|*****************");
            LOGGER.info("\n"+flag+"|body解析异常，用户信息"+ openId + "," + phone + "，" + platform);
            LOGGER.info("\n|*****************");
            return R.ok(CodeEnum.DEFEATED);
        }

        cn.hutool.json.JSONObject bodyJson = null;
        try{
            bodyJson = XML.toJSONObject(body);
        }catch (Exception e){
            //接口返回502 mlb
            return R.ok(CodeEnum.SERVER_INTERNAL_ERROR);
        }
        LOGGER.info("\n " + flag +"返回参数：\n"+bodyJson.toString() + openId + "," + phone + "," + platform);
        JSONObject responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());


        //SID失效 重新调用
        if(responseWrapper.getString("msg").contains("服务出小差了")){
            LOGGER.info("\n###########"+flag+" SID失效重新调用\n");
            request = HttpUtil.createPost(url)
                    .header("Content-type", "application/json;charset=utf-8")
                    .header("Token", platformData.getToken())
                    .body(requestJson.toJSONString()).timeout(25000);
            body = "";
            try {
                body = request.execute().body();
            }catch (Exception e){
                LOGGER.info("\n|*****************");
                LOGGER.info("\n|body解析异常，用户信息"+ openId + "," + phone + "，" + platform);
                LOGGER.info("\n|*****************");
                return R.ok(CodeEnum.DEFEATED);
            }
            bodyJson = XML.toJSONObject(body);
            responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());
        }
        if(responseWrapper.getString("msg").contains("服务出小差了")){
            return R.ok(CodeEnum.CUSTOM);
        }

        String code = responseWrapper.getString("code");
        switch (code){
            case "401":
                //返回validateToken给前台
                return R.ok(CodeEnum.VALIDATE).data(responseWrapper.getString("data"));
            case "0001":
                return R.ok(CodeEnum.DEFEATED);
            case "0002":
                CodeEnum.CUSTOM.setCode(2000);
                if(responseWrapper.getString("msg").contains("饿了么APP") || responseWrapper.getString("msg").contains("服务出小差了")){
                    CodeEnum.CUSTOM.setMsg("请重新领取一下哦！");
                }else if(responseWrapper.getString("msg").contains("您的账户不符合活动要求")){
                    CodeEnum.CUSTOM.setMsg("领取失败，本次不扣积分,如经常领取失败,请联系客服处理");
                }else if(responseWrapper.getString("msg").contains("0003")){
                    CodeEnum.CUSTOM.setMsg("今日领取上限了哦,去领取其他类型红包吧");
                }else{
                    CodeEnum.CUSTOM.setMsg(responseWrapper.getString("msg"));
                }
                return R.ok(CodeEnum.CUSTOM);
            case "0005":
                return R.ok(CodeEnum.SMALL);
            case "10016":
                return R.ok(CodeEnum.INVENTORY);
            case "0000":
                JSONArray data = null;
                try{
                    //这个b接口有时返回jsonarray 有时返回jsonobject
                    data = (JSONArray) JSONArray.parse(responseWrapper.getString("data"));
                }catch (Exception e){
                    return R.ok(CodeEnum.RECEIVE);
                }
                String result = "";
                String luckyMoney = "1";
                for (int i = 0; i < data.size(); i++) {
                    JSONObject resultData = JSONObject.parseObject(data.get(i).toString());
                    String amount = resultData.getString("amount");
                    String threshold = resultData.getString("threshold");
                    String title = resultData.getString("title");
                    if(type == 8){
                        result += "满" + threshold + "减" + amount + " " + title + ",";
                    }
                    if(type == 10){
                        result += "减" + amount + threshold + " " + title + ",";
                    }
                    //小于4不扣积分
                    if(Double.parseDouble(amount)>=5){
                        luckyMoney = "5";
                    }
                    //领取记录
                    LuckyRecord luckyRecord = new LuckyRecord();
                    luckyRecord.setOpenid(openId);
                    luckyRecord.setIsSuccess(Constant.TRUE);
                    luckyRecord.setCreateTime(new Date());
                    luckyRecord.setPlatform(platform);
                    luckyRecord.setLuckyMoney(Double.parseDouble(amount));
                    luckyRecordService.insert(luckyRecord);
                }

                weixinGzhIntegrationRecord(openId,platform, wxUserInfo,type,luckyMoney,configJson);
                LOGGER.info("\n************"+flag+"领取成功\n" + result + "\n" + openId + "," + phone + "," + platform);
                if("1".equals(luckyMoney)){
                    return R.ok().data("因红包金额低于5元,本次不消耗积分,先去领取其他类型红包吧,如有问题请联系客服"/* + result.substring(0,result.length()-1)*/);
                }
                return R.ok().data(result.substring(0,result.length()-1));
        }

        return R.error().data(responseWrapper);
    }


}
